//
//  TempCategoryViewController.m
//  PPDL
//
//  Created by 王洋 on 2019/10/23.
//  Copyright © 2019 王洋. All rights reserved.
//

#import "OYCountDownManager.h"

#import "TempCategoryViewController.h"
#import "PPLabTableViewCell.h"
#import "PPLabCollectionViewCell.h"

#import "PPCategorySectionHeadView.h"
#import "PPCategorySectionFootView.h"

#import "HomeSubscriptButton.h"

#import "GoodListViewController.h"
#import "PPCategoryViewController.h"
#import "MessageCenterViewController.h"

#import "ProductListTableViewCell.h"
#import "GoodDetailViewController.h"


#define tableviewWidth      0.22 * TTScreenWidth
NSString *const k_TempCategoryListItemSource = @"k_TempCategoryListItemSource";

@interface TempCategoryViewController ()
<UITextFieldDelegate,
UITableViewDelegate,
UITableViewDataSource>

@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, strong) UITextField *searchTextField;

@property (nonatomic, strong) HomeSubscriptButton *messageItem;

@property (nonatomic, strong) UITableView *categoryTableview;

@property (nonatomic, strong) UITableView *goodListTableview;

@property (nonatomic, strong) NSMutableArray <PPCategoryModel *> *categoryArray;

@property (nonatomic, strong) NSMutableArray <HomeProductItemModel *> *productListArray;

@property (nonatomic, assign) NSInteger selectIndex;

//@property (nonatomic, assign) BOOL isLoadFinish;

@end

@implementation TempCategoryViewController

- (void)dealloc {
    [kCountDownManager removeSourceWithIdentifier:k_TempCategoryListItemSource];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.isLoadFinish = NO;
    [self initView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self openLoginWithCompletion:^(BOOL isLogin, NSDictionary * _Nonnull options) {
        if (isLogin) {
//            if (!self.isLoadFinish) {
                [self request_CategoryList];
//            }
        }
    }];

    [self refreshUnReadMsgCount];
    [kCountDownManager start];
    [kCountDownManager addSourceWithIdentifier:k_TempCategoryListItemSource];
}

- (void)reloadTime {
    [kCountDownManager reloadSourceWithIdentifier:k_TempCategoryListItemSource];
}

#pragma mark 去消息中心
- (void)goMsgCenter {
    [self.navigationController pushViewController:[MessageCenterViewController new] animated:YES];
}

#pragma mark 刷新未读消息数
- (void)refreshUnReadMsgCount {
    [self.messageItem setCountNum:0];
}

- (void)refreshParam {
    
    self.pageNum = 1;
    self.pageSize = 20;
}

- (void)request_CategoryList {
    
    self.selectIndex = 0;
    NSMutableDictionary *dic = @{}.mutableCopy;
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_SHOP_CATEGORY];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [[TTNoResultManager shareManager] hideNoResultWithView:self.view];
        
        //返回data为字典
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * code = [data valueForKey:@"code"];
            
            //请求成功
            if ([code isEqualToString:@"200"]) {
                
//                self.isLoadFinish = YES;
                //一级赋值
                NSArray *categoryArray = [data valueForKey:@"data"];
                self.categoryArray = @[].mutableCopy;
                if ([categoryArray isKindOfClass:[NSArray class]]) {
                    
                    for (int i = 0; i < categoryArray.count; i++) {
                        
                        NSDictionary *firstDic = categoryArray[i];
                        PPCategoryModel *firstModel = [[PPCategoryModel alloc] init];
                        
                        if ([firstDic isKindOfClass:[NSDictionary class]]) {
                            
                            firstModel.itemTitle = [firstDic valueForKey:@"name"];
                            firstModel.itemID = [firstDic valueForKey:@"id"];
                            
                            if (i==0) {
                                firstModel.isSelect = YES;
                                self.selectIndex = 0;
                            }
                        }
                        [self.categoryArray addObject:firstModel];
                    }
                }
                
                if (self.categoryArray.count > 0) {
                    [self refreshParam];
                    [self request_GoodsList];
                } else {
                    WEAKSELF
                    [[TTNoResultManager shareManager] showNoResultWithStateInView:self.view errorCode:kTTViewStateNoData btnTitle:@"重新加载" didPressButton:^{
                        [weakSelf request_CategoryList];
                    }];
                }
            } else {
                
//                self.isLoadFinish = NO;

                //检查到未登录
                if ([code isEqualToString:@"401"]) {
                    
                    [[TTUserModel sharedObject] initialization];
                    
                    [self openLoginWithCompletion:^(BOOL isLogin, NSDictionary * _Nonnull options) {
                        if (isLogin) {
                            [self request_CategoryList];
                        }
                    }];
                    
                } else {
                    [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                    [SVProgressHUD dismissWithDelay:1];
                    
                    [[TTNoResultManager shareManager] showNoResultWithStateInView:self.view errorCode:kTTViewStateNoData btnTitle:@"重新加载" didPressButton:^{
                        [self request_CategoryList];
                    }];
                }
                
            }
        } else {
            
        }
        
        [self.categoryTableview reloadData];
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
//        self.isLoadFinish = NO;

        WEAKSELF
        [[TTNoResultManager shareManager] showNoResultWithStateInView:self.view errorCode:error.code btnTitle:@"重新加载" didPressButton:^{
            [weakSelf request_CategoryList];
        }];
    }];
}

- (void)request_GoodsList {
    
    [self reloadTime];
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    
    if (self.categoryArray.count > self.selectIndex) {
        [dic setValue:self.categoryArray[self.selectIndex].itemID forKey:@"id"];
    }
    
    [dic setValue:@(self.pageNum) forKey:@"curPage"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_SHOP_FINDSHOPLIST];
    
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [self.goodListTableview.mj_header endRefreshing];
        [self.goodListTableview.mj_footer endRefreshing];
        [[TTNoResultManager shareManager] hideNoResultWithView:self.goodListTableview];
        
        //返回data为字典
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * code = [data valueForKey:@"code"];
            //请求成功
            if ([code isEqualToString:@"200"]) {
                
                NSArray *resultArray = [data valueForKey:@"data"];
                if ([resultArray isKindOfClass:[NSArray class]]) {
                    
                    
                    if (self.pageNum == 1) {
                        self.productListArray = @[].mutableCopy;
                        
                    }
                    
                    if (resultArray.count < self.pageSize) {
                        [self.goodListTableview.mj_footer endRefreshingWithNoMoreData];
                    }
                    
                    for (int i = 0; i < resultArray.count; i++) {
                        NSDictionary *productDic = [resultArray objectAtIndex:i];
                        HomeProductItemModel *productModel = [[HomeProductItemModel alloc] init];
                        productModel.productID =    [productDic valueForKey:@"id"];
                        productModel.productName =  [productDic valueForKey:@"goodsName"];
                        productModel.productImage = [productDic valueForKey:@"coverImgPath"];
                        
                        productModel.auctionPrice = [[productDic valueForKey:@"goodsStartingPrice"] doubleValue];
                        productModel.marketPrice =  [[productDic valueForKey:@"goodsMarketPrice"] doubleValue];
                        
                        productModel.goodDetailType =(PPGoodDetailType)[[productDic valueForKey:@"goodDetailType"] integerValue];
                        productModel.beginTimestamp =  [[productDic valueForKey:@"startTime"] doubleValue];
                        productModel.endTimestamp =    [[productDic valueForKey:@"endTime"] doubleValue];//2019-08-02
                        
                        productModel.countDownSource = k_TempCategoryListItemSource;
                        
                        [self.productListArray addObject:productModel];
                    }
                    
                    if (self.pageNum == 1 && resultArray.count == 0) {
                        WEAKSELF
                        [[TTNoResultManager shareManager] showNoResultWithStateInView:self.goodListTableview errorCode:kTTViewStateNoData btnTitle:@"刷新看看" didPressButton:^{
                            [weakSelf request_GoodsList];
                        }];
                        
                    } else {
                        
                    }
                }
                
            } else {
                
                if (self.pageNum == 1) {
                    [self.productListArray removeAllObjects];
                }
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                [SVProgressHUD dismissWithDelay:1];
                
                WEAKSELF
                [[TTNoResultManager shareManager] showNoResultWithStateInView:self.goodListTableview errorCode:kTTViewStateNoData btnTitle:@"重新加载" didPressButton:^{
                    [weakSelf request_GoodsList];
                }];
            }
            
        } else {
            
            if (self.pageNum == 1) {
                [self.productListArray removeAllObjects];
            }
            
            [SVProgressHUD showErrorWithStatus:@"返回为空"];
            [SVProgressHUD dismissWithDelay:1];
        }
        
        [self.goodListTableview reloadData];
        
    } FailedBlock:^(NSError * _Nonnull error) {
//        [SVProgressHUD dismiss];

        WEAKSELF
        [[TTNoResultManager shareManager] showNoResultWithStateInView:self.view errorCode:error.code btnTitle:@"重新加载" didPressButton:^{
            [weakSelf request_GoodsList];
        }];
    }];
}

- (void)initView {
    
    self.view.backgroundColor = UIColorHex(0xdddddd);
    [self.view addSubview:self.categoryTableview];
    [self.view addSubview:self.goodListTableview];
    self.navigationItem.titleView = self.searchTextField;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.messageItem];
    self.searchTextField.frame = CGRectMake(0, 0, TTScreenWidth - 30, 32);
    
    [self.categoryTableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0.5);
        make.left.bottom.mas_equalTo(0);
        make.width.mas_equalTo(tableviewWidth);
    }];
    
    [self.goodListTableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0.5);
        make.left.mas_equalTo(self.categoryTableview.mas_right).offset(0.5);
        make.right.bottom.mas_equalTo(0);
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self doSearchAction];
    
    return YES;
}

- (void)doSearchAction {
    
    [self.searchTextField resignFirstResponder];
    
    if (self.searchTextField.text.length) {
        GoodListViewController *VC = [[GoodListViewController alloc] init];
        VC.itemTitle = self.searchTextField.text;;
        VC.type = PP_GOODLIST_TYPE_SEARCH;
        [self.navigationController pushViewController:VC animated:YES];
    } else {
        [self alert:@"请输入搜索词"];
    }
}

#pragma mark tableview delegate & datasource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == self.categoryTableview) {
        PPLabTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PPLabTableViewCellID" forIndexPath:indexPath];
        
        if (self.categoryArray.count > indexPath.row) {
            [cell fillCellWithModel:self.categoryArray[indexPath.row]];
        }
        
        return cell;
    } else {
        
        ProductListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ProductListTableViewCellID" forIndexPath:indexPath];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
        
        if (self.productListArray.count > indexPath.row) {
            [cell fillCellWithModel:self.productListArray[indexPath.row]];
        }
        
        WEAKSELF
        cell.countDownZero = ^(HomeProductItemModel * _Nonnull model) {
            if (indexPath.row < weakSelf.productListArray.count) {
                [weakSelf.productListArray replaceObjectAtIndex:indexPath.row withObject:model];//复用的时候永用到
            }
        };
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == self.categoryTableview) {
        return 50;
    } else {
        return TTScreenWidth/4 + 16;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (tableView == self.categoryTableview) {
        return self.categoryArray.count;
    } else {
        return self.productListArray.count;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == self.categoryTableview) {
        
        self.selectIndex = indexPath.row;
        for (int i = 0; i < self.categoryArray.count; i++) {
            if (i!=indexPath.row) {
                self.categoryArray[i].isSelect = NO;
            } else {
                self.categoryArray[i].isSelect = YES;
            }
        }
        [self.categoryTableview reloadData];
        [self refreshParam];
        [self request_GoodsList];
        
    } else {
        
        if (self.categoryArray.count > self.selectIndex) {
            GoodDetailViewController *detailVC = [[GoodDetailViewController alloc] init];
            detailVC.goodsID = self.productListArray[indexPath.row].productID;
            detailVC.type = self.productListArray[indexPath.row].goodDetailType;
//            detailVC.type = PPMallPaiGoodsDetail;
            [self.navigationController pushViewController:detailVC animated:YES];
        }

    }
}

- (UITableView *)categoryTableview {
    if (!_categoryTableview) {
        _categoryTableview = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _categoryTableview.backgroundColor = PP_Default_Color_Gray_F1F1F1;
        _categoryTableview.delegate = self;
        _categoryTableview.dataSource = self;
        _categoryTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _categoryTableview.showsHorizontalScrollIndicator = NO;
        _categoryTableview.showsVerticalScrollIndicator = NO;
        
        _categoryTableview.estimatedSectionHeaderHeight = 0;
        _categoryTableview.estimatedSectionFooterHeight = 0;
        _categoryTableview.estimatedRowHeight = 0;
        
        [_categoryTableview registerNib:[UINib nibWithNibName:@"PPLabTableViewCell" bundle:nil] forCellReuseIdentifier:@"PPLabTableViewCellID"];
        
    }
    return _categoryTableview;
}

- (UITableView *)goodListTableview {
    if (!_goodListTableview) {
        _goodListTableview = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _goodListTableview.backgroundColor = UIColorHex(0xffffff);
        _goodListTableview.delegate = self;
        _goodListTableview.dataSource = self;
        _goodListTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _goodListTableview.showsHorizontalScrollIndicator = NO;
        _goodListTableview.showsVerticalScrollIndicator = NO;
        
        _goodListTableview.estimatedSectionHeaderHeight = 0;
        _goodListTableview.estimatedSectionFooterHeight = 0;
        _goodListTableview.estimatedRowHeight = 0;
        
        [_goodListTableview registerNib:[UINib nibWithNibName:@"ProductListTableViewCell" bundle:nil] forCellReuseIdentifier:@"ProductListTableViewCellID"];
        
        WEAKSELF
        
        _goodListTableview.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            [weakSelf refreshParam];
            [weakSelf request_GoodsList];
        }];
        
        _goodListTableview.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            weakSelf.pageNum ++;
            [weakSelf request_GoodsList];
        }];


    }
    return _goodListTableview;
}

- (UITextField *)searchTextField {
    if (!_searchTextField) {
        _searchTextField = [[UITextField alloc]init];
        _searchTextField.backgroundColor = UIColorHex(0xf0f0f0);
        _searchTextField.delegate = self;
        _searchTextField.returnKeyType = UIReturnKeySearch;
        _searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _searchTextField.placeholder = @"输入关键词搜索";
        _searchTextField.font = [UIFont fontWithName:@"Arial" size:14];
        _searchTextField.frame = CGRectMake(0, 6, TTScreenWidth - 60, 32);
        _searchTextField.layer.cornerRadius = 6;
        _searchTextField.layer.masksToBounds = YES;
        
        UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        searchBtn.frame = CGRectMake(0, 0, 30, 30);
        searchBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        [searchBtn addTarget:self action:@selector(doSearchAction) forControlEvents:UIControlEventTouchUpInside];
        [searchBtn setImage:[UIImage imageNamed:@"search_icon"] forState:UIControlStateNormal];
        
        _searchTextField.leftView = searchBtn;
        _searchTextField.leftViewMode = UITextFieldViewModeAlways;
    }
    return _searchTextField;
}

- (NSMutableArray<PPCategoryModel *> *)categoryArray {
    if (!_categoryArray) {
        _categoryArray = @[].mutableCopy;
    }
    return _categoryArray;
}

- (HomeSubscriptButton *)messageItem {
    if (!_messageItem) {
        _messageItem = [[HomeSubscriptButton alloc] initWithSize:CGSizeMake(40, 40)];
        [_messageItem.topButton setImage:[UIImage imageNamed:@"homeMsg"] forState:UIControlStateNormal];;
        _messageItem.userInteractionEnabled = YES;
        [_messageItem.topButton addTarget:self action:@selector(goMsgCenter) forControlEvents:UIControlEventTouchUpInside];
    }
    return _messageItem;
}

@end
